package com.ceuer.demo.deadlock;

//死锁：多个线程互相拥抱着对方需要的资源，然后形成僵持
public class Deadlock {
	public static void main(String[] args) {
		Makeup g1=new Makeup(0, "灰姑娘");
		Makeup g2=new Makeup(1, "白雪公主");
		
		new Thread(g1,g1.girlName).start();
		new Thread(g2,g2.girlName).start();
	}
}

//口红
class Lipstick{}

//镜子
class Mirror{}

//化妆
class Makeup implements Runnable{
	//使用静态修饰保证只有一份
	static Lipstick lipstick=new Lipstick();
	static Mirror mirror=new Mirror();
	
	int choose;//选择那个
	String girlName;//化妆的女孩
	
	public Makeup(int choose, String girlName) {
		this.choose = choose;
		this.girlName = girlName;
	}
	
	@Override
	public void run() {
		makeup();
	}
	
	//化妆:互相持有对方的锁，就是需要拿到对方的资源
	private void makeup(){
		if(choose==0){
			synchronized (lipstick){//获得口红的锁
				System.out.println(Thread.currentThread().getName()+"获得口红的锁");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (mirror){//获得镜子的锁
					System.out.println(Thread.currentThread().getName()+"获得镜子的锁");
				}
			}
		}else{
			synchronized (mirror){//获得镜子的锁
				System.out.println(Thread.currentThread().getName()+"获得镜子的锁");
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (lipstick){//获得口红的锁
					System.out.println(Thread.currentThread().getName()+"获得口红的锁");
				}
			}
		}
	}
}
